# Create your views here.
from django.template import loader, RequestContext
from addons.models import addon
from django.http import HttpResponse


#Default view of the page
def index(request):
    latest_addon_list = addon.objects.all().order_by('-addon_pub_date')[:5]
    t = loader.get_template('addons/index.html')
    c = RequestContext(request, {'latest_addon_list': latest_addon_list})
    return HttpResponse(t.render(c))


#Detail view for addons
def detail(request, addon_id):
    not_allowed = True
    addon_details = addon.objects.get(pk=addon_id)
    for voted in addon_details.addon_voted_by.all():
        if(voted.user.username == request.user.username):
            not_allowed = True
            break
        else:
            not_allowed = False
    if(addon_details.addon_vote_plus == 0 and
       addon_details.addon_vote_minus == 0):
        vote_m = 0
        vote = False
        upvote = "0%"
        downvote = "0%"
    else:
        vote = True
        vote_m = float(float(100) / float(addon_details.addon_vote_plus +
                                          addon_details.addon_vote_minus))
        upvote = str(int(round(addon_details.addon_vote_plus * vote_m))) + '%'
        downvote = str(int(round(addon_details.addon_vote_minus *
                                 vote_m))) + '%'
    t = loader.get_template('addons/detail.html')
    c = RequestContext(request, {'addon_details': addon_details,
                                 'next': request.get_full_path(),
                                 'addon_title': addon_details.addon_name,
                                 'vote': vote,
                                 'upvote': upvote,
                                 'downvote': downvote,
                                 'vote_m': vote_m,
                                 'not_allowed': not_allowed})
    return HttpResponse(t.render(c))
